package torres.map.areaeffect;

import torres.entity.Entity;
import torres.fileIO.ClassContainer;
import torres.fileIO.BasicContainer;

/**
 * @author Torres
 * A special kind of AreaEffect that heals the Entity. Has a certain rate and
 * heal value.
 */
public class HealDamage implements AreaEffect {
	
	private int damage;
	private int seconds;
	private long elapsed;
	private long lastUsed;
	
	/**
	 * Creates a new HealDamage AreaEffect with the default rate of 1 second and default damage of 1.
	 */
	public HealDamage() {
		
		this.damage = 1;
		this.seconds = 1;
		this.elapsed = 0;
		this.lastUsed = 0;
	}
	
	/**
	 * Creates a new HealDamage AreaEffect with the specified value to be healed, and the specified rate of heal.
	 * @param damage Amount of damage to be healed.
	 * @param seconds Rate of heal area effect in seconds.
	 */
	public HealDamage(int damage, int seconds) {
		
		this.damage = damage;
		this.seconds = seconds;
		this.elapsed = 0;
		this.lastUsed = 0;
	}
	
	/* (non-Javadoc)
	 * @see torres.map.areaeffect.AreaEffect#applyEffect(torres.entity.Entity)
	 */
	public boolean applyEffect(Entity e) {
		
		if(elapsed >= ((long) 1000000000 * seconds)) {
			
			e.healDamage(damage);

			this.lastUsed = System.nanoTime();
			this.elapsed = 0;
			return true;
		}
		else {
			
			this.elapsed = System.nanoTime() - lastUsed;
			return false;
		}
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		
		return "Amount of damage healed = " + damage;
	}

	/* (non-Javadoc)
	 * @see torres.fileIO.Saveable#save()
	 */
	@Override
	public ClassContainer save() {
		ClassContainer curClass = new ClassContainer("HealDamage");
		curClass.addProperty(new BasicContainer("damage", damage));
		curClass.addProperty(new BasicContainer("seconds", seconds));
		curClass.addProperty(new BasicContainer("elapsed", Long.toString(elapsed)));
		curClass.addProperty(new BasicContainer("lastUsed", Long.toString(elapsed)));
		
		return curClass;
	}

	/* (non-Javadoc)
	 * @see torres.fileIO.Saveable#load(torres.fileIO.ClassContainer)
	 */
	@Override
	public void load(ClassContainer classContainer) {
		BasicContainer damageCont = (BasicContainer)classContainer.getProperty("damage");
		damage = Integer.parseInt((String)damageCont.getValue());
		BasicContainer secondsCont = (BasicContainer)classContainer.getProperty("seconds");
		seconds = Integer.parseInt((String)secondsCont.getValue());
		BasicContainer elapsedCont = (BasicContainer)classContainer.getProperty("elapsed");
		elapsed = Long.parseLong((String)elapsedCont.getValue());
		BasicContainer lastUsedCont = (BasicContainer)classContainer.getProperty("lastUsed");
		lastUsed = Long.parseLong((String)lastUsedCont.getValue());
		
	}
}
